package com.yoke.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * Created by jiangzeyin on 2017/3/9.
 */
public class HttpUtil {

    public static String post(String url, HttpEntity entity) throws IOException {
        HttpPost httppost = new HttpPost(url);
        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
        httppost.setEntity(entity);
        HttpResponse response = closeableHttpClient.execute(httppost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity resEntity = response.getEntity();
            return EntityUtils.toString(resEntity);
        } else {
            HttpEntity resEntity = response.getEntity();
            System.out.println(resEntity.getContentLength());
            System.out.println(EntityUtils.toString(resEntity));
            return "error:" + statusCode;
        }
    }

    public static String delete(String url) throws IOException {
        HttpDelete delete = new HttpDelete(url);
        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().
                setUserAgent("Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0")

                .build();
        HttpResponse response = closeableHttpClient.execute(delete);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity resEntity = response.getEntity();
            return EntityUtils.toString(resEntity);
        } else {
            HttpEntity resEntity = response.getEntity();
            System.out.println(EntityUtils.toString(resEntity));
            return "error:" + statusCode;
        }
    }

}
